#!/usr/bin/env ruby
$:.push("./plugins")
$:.push("./lib")
require 'dchub'
require 'signal'
require 'logger'
require 'basiclib'
require 'plugin'
require 'yaml'
require 'fileutils'
require 'core.rb'

class DCControl < Plugin
	
	def initialize()

		puts "running cli control/chat for ruby DC++.."
                puts "loading config..."
                @cfgpath= (ENV['APPDATA']==nil ? ENV['HOME'] : ENV['APPDATA'])+"/.rudcpp" #are we in windows or in unix?
                FileUtils::mkdir(@cfgpath) unless File.exists?(@cfgpath)
                
                if File.exists?(@cfgpath+"/config.yaml")
                        puts "found config"
                        @settings=YAML::load_file(@cfgpath+"/config.yaml")
                else
                        puts "config not found! running with defaults"
                        @settings=Hash.new
                end
                
		@settings[:core_port]=1555 unless @settings.has_key?(:core_port)
                @settings[:hubs]={} unless @settings.has_key?(:hubs)
		@hubs=[]

                puts "forking core"
			@corepid=fork{
                        core=RuDcCore.new(@settings[:core_port],"",{:selfdebug=>STDOUT, :debugout=>STDOUT})
			#core=RuDcCore.new(@settings[:core_port],"",{:selfdebug=>STDOUT})
                        }

                @coreURI="druby://localhost:#{@settings[:core_port].to_s}"
                sleep 2
                super(@coreURI,"control")
                sleep 1
                wait_register(@core,"control")
		puts "control system ready"
	end

	def runcli
		@settings[:hubs]["clihub"]=Hash.new unless @settings[:hubs].has_key?("clihub")
		
		#running plugin
		startPlugin(DCHub,@coreURI,"clihub",@settings[:hub_settings])
		wait_register(@core,"clihub")
		@hubs.push(@core.plugins["clihub"])
		
		puts "hub ready"
		@core.connectPlugs("clihub",:chatmsg,"control",:chatmsg)
		@core.connectPlugs("control",:toHub,"clihub",:chatToHub)
		
		puts("---------------")
		puts("wait for your commands. (starts with /)")
		cmd=""
		while cmd!="/quit\n"
			#putc ">"
			cmd=STDIN.gets
			case cmd
				when "/connect\n"
					puts "running hub"
					@core.runPlugin("clihub")
				when "/quit\n"
					puts "/quit recived"
				else
					emit(:toHub,cmd[0...cmd.length-1]+"|")
			end
		end
		puts "saving settings..."
		save_settings
		puts "killing core:"
		Process.kill("TERM",@corepid)
		DRb.thread.join
	end

	def save_settings
		@hubs.each{|hub|
			@settings[:hubs][hub.name]=hub.settings
		}
		out=File.new("#{@cfgpath}/config.yaml","w+")
		out.puts(YAML::dump(@settings))
	end

	def chatmsg(msg)
		puts msg
	end
end

if __FILE__==$0
	control=DCControl.new
	control.runcli
end

